package gold.digger;

import gold.utils.InputUtil;
import gold.vo.TreeNode;

/**
 * Created by fanzhenyu02 on 2020/6/27.
 * common problem solver template.
 */
public class LC106 {
    public long startExecuteTime = System.currentTimeMillis();


    class Solution {
        public TreeNode buildTree(int[] inorder, int[] postorder) {
            return buildTreeRecur(inorder, postorder, 0, inorder.length - 1, 0, postorder.length - 1);
        }

        public TreeNode buildTreeRecur(int[] inorder, int[] postorder,
                                       int inStart, int inEnd, int postStart, int postEnd) {
            if (inStart > inEnd) return null;
            if (inStart == inEnd) return new TreeNode(inorder[inStart]);

            TreeNode curRoot = new TreeNode(postorder[postEnd]);
            int rootIndexInInOrder = findIndex(inorder, postorder[postEnd]);
            curRoot.left = buildTreeRecur(inorder, postorder, inStart, rootIndexInInOrder - 1, postStart, postStart + rootIndexInInOrder - 1 - inStart);
            curRoot.right = buildTreeRecur(inorder, postorder, rootIndexInInOrder + 1, inEnd, postEnd - inEnd + rootIndexInInOrder, postEnd - 1);
            return curRoot;
        }

        int findIndex(int[] arr, int target) {
            for (int i = 0; i < arr.length; i++) {
                if (arr[i] == target) return i;
            }

            return -1;
        }
    }


    public void run() {
        Solution solution = new Solution();
        int[] inorder = InputUtil.toIntegerArray("[1,2,3,4]");
        int[] postorder = InputUtil.toIntegerArray("[3,2,4,1]");

        System.out.println(solution.buildTree(inorder, postorder));
    }

    public static void main(String[] args) throws Exception {
        LC106 an = new LC106();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
